package com.runda.partypolicy.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

/**
 * author:  RD_YH
 * date:    2018/11/13
 * version: v1.0
 * description: 通用方法
 */
public class CommonUtils {

    /**
     * 获取当前程序版本名字
     *
     * @param context
     * @return
     */
    public static String getCurrentVersionName(Context context) {
        String version = null;
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 获取当前程序版本号
     *
     * @param context
     * @return
     */
    public static int getCurrentVersionCode(Context context) {
        int version = 0;
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            version = info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }
    /**
     * 版本比较（x.x.x）
     *
     * @param newVersion
     * @param oldVersion
     * @return
     * @throws
     */
    public static int compareVersion(String newVersion, String oldVersion) throws Exception {
        if (newVersion == null || oldVersion == null) {
            throw new Exception("compareVersion error:illegal params.");
        }
        String[] versionArray1 = newVersion.split("\\.");//注意此处为正则匹配，不能用.；
        String[] versionArray2 = oldVersion.split("\\.");
        int idx = 0;
        int minLength = Math.min(versionArray1.length, versionArray2.length);//取最小长度值
        int diff = 0;
        while (idx < minLength
                && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0//先比较长度
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {//再比较字符
            ++idx;
        }
        //如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }

}
